package com.prs.crm.action.crm;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.courser.struts.BaseAction;
import org.courser.ui.PaginationSupport;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.prs.crm.annotation.Clew;
import com.prs.crm.context.AppContext;
import com.prs.crm.context.Constrains;
import com.prs.crm.context.ToolKits;
import com.prs.crm.domain.crm.Customer;
import com.prs.crm.domain.crm.CustomerLevel;
import com.prs.crm.domain.crm.Liaison;
import com.prs.crm.domain.crm.LiaisonCostItem;
import com.prs.crm.domain.crm.LiaisonCritique;
import com.prs.crm.domain.crm.LiaisonEvolve;
import com.prs.crm.domain.crm.LiaisonReason;
import com.prs.crm.domain.crm.LiaisonWay;
import com.prs.crm.domain.crm.Linkman;
import com.prs.crm.exception.InValidDeleteException;
import com.prs.crm.report.ReportUtils;
import com.prs.crm.service.crm.CustomerAppointService;
import com.prs.crm.service.crm.CustomerLevelService;
import com.prs.crm.service.crm.CustomerService;
import com.prs.crm.service.crm.LiaisonCostItemService;
import com.prs.crm.service.crm.LiaisonCritiqueService;
import com.prs.crm.service.crm.LiaisonEvolveService;
import com.prs.crm.service.crm.LiaisonReasonService;
import com.prs.crm.service.crm.LiaisonService;
import com.prs.crm.service.crm.LiaisonWayService;
import com.prs.crm.service.crm.LinkmanService;

public class LiaisonAction extends BaseAction{
	
	private static final long serialVersionUID = 1L;
	
	private Liaison liaison;
	private LiaisonService liaisonService;
	private PaginationSupport pagination;
	private Integer[] ids;
	
	private LiaisonCritique liaisonCritique;
	private Customer customer;
	private CustomerService customerService;
	
	private LiaisonEvolveService liaisonEvolveService;
	private LiaisonCostItemService liaisonCostItemService;
	private LiaisonReasonService liaisonReasonService;
	private LiaisonWayService liaisonWayService;
	private LinkmanService linkmanService;
	private CustomerAppointService customerAppointService;
	private CustomerLevelService customerLevelService;
	private LiaisonCritiqueService liaisonCritiqueService;
	
	private List<LiaisonEvolve> liaisonEvolves;
	private List<LiaisonCostItem> liaisonCostItems;
	private List<LiaisonReason> liaisonReasons;
	private List<LiaisonWay> liaisonWays;
	private List<Linkman> linkmans;
	private List<CustomerLevel> customerLevels;
	private Collection<LiaisonCritique> liaisonCritiques;
	
	private File upload;
	private String uploadFileName;
	
	private Integer[] items;
	private Double[] num;
	
	private Date currentDate;
	private Liaison upLiaison;
	private boolean flag;
	private String tradeIds;
	
	@Action("listLiaison")
	public String execute() {
		return SUCCESS;
	}
	@Action("listLiaisonByTrade")
	public String listLiaisonByTrade(){
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(Liaison.class);
		criteria.addOrder(Order.desc("recordTime"));
		pagination = this.getPaginationHelper().prepare(pagination);
		if(tradeIds != null){
			if(!"all".equals(tradeIds)){
				tradeIds = tradeIds.split(",")[0];
				if(ToolKits.isInteger(tradeIds)){
					criteria.createAlias("customer", "c");
					criteria.createAlias("c.trade", "tr");
					criteria.add(Restrictions.eq("tr.id", Integer.parseInt(tradeIds)));
				}
			}
		}
		this.setPagination(this.getLiaisonService().listByPage(criteria, pagination));
		return SUCCESS;
	}
	
	@Action("listCritiqueLiaison")
	public String listCritiqueLiaison() {
		return SUCCESS;
	}
	@Action("listCritiqueLiaisonByLevel")
	public String listCritiqueLiaisonByLevel(){
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(Liaison.class);
		criteria.addOrder(Order.desc("recordTime"));
		if(tradeIds != null){
			if(!"all".equals(tradeIds)){
				tradeIds = ReportUtils.URLDecode(tradeIds).trim();
				if(tradeIds.indexOf("trade") != -1){
					tradeIds = tradeIds.split(",")[0];
					criteria.createAlias("customer", "c");
					criteria.createAlias("c.trade", "tr");
					criteria.add(Restrictions.eq("tr.id", Integer.parseInt(tradeIds)));
				}else if(tradeIds.indexOf("level") != -1){
					tradeIds = tradeIds.split(",")[0];
					criteria.createAlias("customer", "c");
					criteria.createAlias("c.level", "le");
					criteria.add(Restrictions.eq("le.id", Integer.parseInt(tradeIds)));
				}else if(tradeIds.split(",")[0].indexOf("dept") != -1){
					Collection<Integer> personIds = new ArrayList<Integer>();
					for(String val : tradeIds.split(",")){
						if(val.indexOf("dept") == -1){
							personIds.add(Integer.parseInt(val));
						}
					}
					if(personIds.size() > 0){
						criteria.createAlias("recorder", "rec");
						criteria.add(Restrictions.in("rec.id", personIds));
					}
				}else if(ToolKits.isInteger(tradeIds.split(",")[0])){
					criteria.createAlias("recorder", "rec");
					criteria.add(Restrictions.eq("rec.id", Integer.parseInt(tradeIds.split(",")[0])));
				}
			}
		}
		
		pagination = this.getPaginationHelper().prepare(pagination);		
		this.setPagination(this.getLiaisonService().listByPage(criteria, pagination));
		return SUCCESS;
	}
	
	@Action("editCritiqueLiaison")
	public String editCritiqueLiaison() {
		return SUCCESS;
	}
	
	@Clew(results={"success"})
	@Action(value="submitCritiqueLiaison",results={@Result(name="success",type="redirect",location="listCritiqueLiaison")})
	public String submitCritiqueLiaison() {
		liaisonCritique.setLiaison(liaison);
		this.getLiaisonCritiqueService().submitLiaisonCritique(liaisonCritique, upload, uploadFileName);
		this.setPrompt("提交联络点评成功");
		return SUCCESS;
	}
	
	@Action("viewLiaisonCritique")
	public String viewLiaisonCritique() {
		return SUCCESS;
	}
	
	@Action("listLiaisonCustomer")
	public String listLiaisonCustomer() {
		return SUCCESS;
	}
	@Action("listLiaisonCustomerByTrade")
	public String listLiaisonCustomerByTrade(){
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(Customer.class);
		criteria.addOrder(Order.desc("recordTime"));
		pagination = this.getPaginationHelper().prepare(pagination);
		if(tradeIds != null){
			if(!"all".equals(tradeIds)){
				String ids = tradeIds.split(",")[0];
				if(ToolKits.isInteger(ids)){
					criteria.createAlias("trade", "tr");
					criteria.add(Restrictions.eq("tr.id", Integer.parseInt(ids)));
				}
			}
		}
		this.setPagination(this.getCustomerService().listByPage(criteria, pagination));
		return SUCCESS;
	}
	
	
	@Action("listLiaisonNewCustomer")
	public String listLiaisonNewCustomer() {        
		return SUCCESS;
	}
	@Action("listLiaisonNewCustomerByTrade")
	public String listLiaisonNewCustomerByTrade(){
		List<Customer> results = new ArrayList<Customer>();
		Collection<Customer> customers = this.getCustomerService().getAllNoneLiaisonCustomers(tradeIds);
		for(Customer customer : customers) {
			results.add(customer);
		}
		pagination = this.getPaginationHelper().prepare(pagination);
		pagination.setTotalCount(results.size());
		int totalPage = pagination.getTotalCount() / pagination.getPageSize();
        if(totalPage * pagination.getPageSize() < pagination.getTotalCount())
              totalPage++;
        pagination.setTotalPage(totalPage);  
        
        int pageCount = 15;
        int start = pagination.getStartIndex() / pageCount;
        List<Customer> page = new ArrayList<Customer>();
        int end = 0;
        if(((start + 1) * 15) < results.size()) {
        	end = (start + 1) * 15;
        }else {
        	end = results.size();
        }
        for(int i=(start * 15);i<end ;i++) {
        	page.add(results.get(i));
        }
        pagination.setItems(page);
		return SUCCESS;
	}
	
	
	@Action("listTodayDueLiaison")
	public String listTodayDueLiaison() {
		pagination = this.getPaginationHelper().prepare(pagination);
		Collection<Liaison> liaisons = this.getLiaisonService().getTodayDueLiaison();
		List<Liaison> results = new ArrayList<Liaison>();
		
		for(Liaison liaison : liaisons) {
			results.add(liaison);
		}
		pagination.setTotalCount(results.size());
		int totalPage = pagination.getTotalCount() / pagination.getPageSize();
        if(totalPage * pagination.getPageSize() < pagination.getTotalCount())
              totalPage++;
        pagination.setTotalPage(totalPage);
        
        int pageCount = 15;
        int start = pagination.getStartIndex() / pageCount;
        List<Liaison> page = new ArrayList<Liaison>();
        int end = 0;
        if(((start + 1) * 15) < results.size()) {
        	end = (start + 1) * 15;
        }else {
        	end = results.size();
        }
        for(int i=(start * 15);i<end ;i++) {
        	page.add(results.get(i));
        }
        pagination.setItems(page);
        
		return SUCCESS;
	}	
	@Clew(results={"success"})
	@Action(value="submitTodayDueLiaison",results={@Result(name="success",type="redirect",location="listTodayDueLiaison")})
	public String submitPayroll() {
		this.setPrompt("登记成功");
		this.getLiaisonService().save(liaison);
		return SUCCESS;
	}
	
	@Action("editTodayDueLiaison")
	public String editTodayDueLiaison() {
		this.setLiaisonEvolves(this.getLiaisonEvolveService().getAllLiaisonEvolve());
		this.setLiaisonCostItems(this.getLiaisonCostItemService().getAllLiaisonCostItem());
		this.setLiaisonReasons(this.getLiaisonReasonService().getAllLiaisonReason());
		this.setLiaisonWays(this.getLiaisonWayService().getAllLiaisonWay());
		this.setLinkmans(this.getLinkmanService().getLinkmanByCustomer(customer));
		customerLevels = this.getCustomerLevelService().getAllCustomerLevel();
		
		currentDate = new Date();
		int count = this.getLiaisonCostItems().size();
		num = new Double[count];
		for(int i=0;i<count;i++) {
			num[i] = 0.00;
		}
		return SUCCESS;
	}

	@Action("listTodayDueLiaison4Appoint")
	public String listTodayDueLiaison4Appoint() {
		pagination = this.getPaginationHelper().prepare(pagination);
		Collection<Liaison> liaisons = this.getCustomerAppointService().getTodayDueLiaison4Appoint(AppContext.getAccountContext().currentUser());
		List<Liaison> results = new ArrayList<Liaison>();
		for(Liaison liaison : liaisons) {
			results.add(liaison);
		}
		pagination.setItems(results);
		pagination.setTotalCount(results.size());
		int totalPage = pagination.getTotalCount() / pagination.getPageSize();
        if(totalPage * pagination.getPageSize() < pagination.getTotalCount())
              totalPage++;
        pagination.setTotalPage(totalPage);
		return SUCCESS;
	}
	
	@Action("editLiaison")
	public String edit() {
		this.setLiaisonEvolves(this.getLiaisonEvolveService().getAllLiaisonEvolve());
		this.setLiaisonCostItems(this.getLiaisonCostItemService().getAllLiaisonCostItem());
		this.setLiaisonReasons(this.getLiaisonReasonService().getAllLiaisonReason());
		this.setLiaisonWays(this.getLiaisonWayService().getAllLiaisonWay());
		this.setLinkmans(this.getLinkmanService().getLinkmanByCustomer(customer));
		customerLevels = this.getCustomerLevelService().getAllCustomerLevel();
		
		currentDate = new Date();
		int count = this.getLiaisonCostItems().size();
		num = new Double[count];
		for(int i=0;i<count;i++) {
			num[i] = 0.00;
		}
		return SUCCESS;
	}
	
	@Clew(results={"success"})
	@Action(value="saveLiaison",results={@Result(name="success",type="redirect",location="listLiaisonCustomer"),
			@Result(name="error",type="chain",location="editLiaison")})
	public String save() {	
		if(liaison.getReason()==null){
			addActionError("联络理由不能为空");
			return ERROR;
		}if(liaison.getWay()==null){
			addActionError("联络方式不能为空");
			return ERROR;
		}
		if(liaison.getEvolve()==null){
			addActionError("联络进展不能为空");
			return ERROR;
		}
		
		if(liaison.getLiaisonTime()==null){
			addActionError("联系时间不能为空");
			return ERROR;
		}
		if(liaison.getNextLiaison()==null){
			addActionError("下次联系时间不能为空");
			return ERROR;
		}
		if(upLiaison != null) {
			liaison.setUpLiaison(upLiaison);
			
			upLiaison.setFlag("1");
			this.getLiaisonService().save(upLiaison);
		}
		liaison.setCustomer(customer);
		liaison.setState(Constrains.TASK_AUDITING);
		this.getLiaisonService().saveLiaison(liaison, upload, uploadFileName, items, num);
		this.setPrompt("提交客户联络成功");
		return SUCCESS;
	}
	
	@Action(value="removeLiaison",results={@Result(name="success",type="redirect",location="listLiaison"),
			@Result(name="error",type="chain",location="listLiaison")})
	public String remove() {
		try {
		if(ids == null) {
			this.addActionError("请选择要删除的联络信息");
			return ERROR;
		}
		this.getLiaisonService().batchRemove(ids);
		return SUCCESS;
		} catch (InValidDeleteException e) {
			// TODO: handle exception
			return ERROR;
		}
	}
	
	
	@Action("listDelegateLiaison")
	public String listDelegateLiaison() {
		return SUCCESS;
	}
	@Action("listDelegateLiaisonByTrade")
	public String listDelegateLiaisonByTrade(){
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(Liaison.class);
		criteria.add(Restrictions.eq("recorder", AppContext.getAccountContext().currentUser()));
		criteria.addOrder(Order.desc("recordTime"));
		if(tradeIds != null){
			if(!"all".equals(tradeIds)){
				tradeIds = ReportUtils.URLDecode(tradeIds).trim();
				if(tradeIds.indexOf("trade") != -1){
					tradeIds = tradeIds.split(",")[0];
					criteria.createAlias("customer", "c");
					criteria.createAlias("c.trade", "tr");
					criteria.add(Restrictions.eq("tr.id", Integer.parseInt(tradeIds)));
				}else if(tradeIds.indexOf("level") != -1){
					tradeIds = tradeIds.split(",")[0];
					criteria.createAlias("customer", "c");
					criteria.createAlias("c.level", "le");
					criteria.add(Restrictions.eq("le.id", Integer.parseInt(tradeIds)));
				}
			}
		}
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getLiaisonService().listByPage(criteria, pagination));
		return SUCCESS;
	}
	
	@Action("viewLiaison")
	public String view() {
		liaisonCritiques = this.getLiaisonCritiqueService().getLiaisonCritique(liaison);
		return SUCCESS;
	}
	
	@Action("listLiaisonCritique")
	public String listLiaisonCritique() {
		return SUCCESS;
	}
	@Action("listLiaisonCritiqueByLevel")
	public String listLiaisonCritiqueByLevel(){
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(LiaisonCritique.class);
		criteria.addOrder(Order.desc("recordTime"));
		if(tradeIds != null){
			if(!"all".equals(tradeIds)){
				tradeIds = ReportUtils.URLDecode(tradeIds).trim();
				if(tradeIds.indexOf("trade") != -1){
					tradeIds = tradeIds.split(",")[0];
					criteria.createAlias("customer", "c");
					criteria.createAlias("c.trade", "tr");
					criteria.add(Restrictions.eq("tr.id", Integer.parseInt(tradeIds)));
				}else if(tradeIds.indexOf("level") != -1){
					tradeIds = tradeIds.split(",")[0];
					criteria.createAlias("customer", "c");
					criteria.createAlias("c.level", "le");
					criteria.add(Restrictions.eq("le.id", Integer.parseInt(tradeIds)));
				}else if(tradeIds.split(",")[0].indexOf("dept") != -1){
					Collection<Integer> personIds = new ArrayList<Integer>();
					for(String val : tradeIds.split(",")){
						if(val.indexOf("dept") == -1){
							personIds.add(Integer.parseInt(val));
						}
					}
					if(personIds.size() > 0){
						criteria.createAlias("recorder", "rec");
						criteria.add(Restrictions.in("rec.id", personIds));
					}
				}else if(ToolKits.isInteger(tradeIds.split(",")[0])){
					criteria.createAlias("recorder", "rec");
					criteria.add(Restrictions.eq("rec.id", Integer.parseInt(tradeIds.split(",")[0])));
				}
			}
		}
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getLiaisonCritiqueService().listByPage(criteria, pagination));
		return SUCCESS;
	}
	
	public Liaison getLiaison() {
		return liaison;
	}
	public void setLiaison(Liaison liaison) {
		this.liaison = liaison;
	}
	public LiaisonService getLiaisonService() {
		return liaisonService;
	}
	public void setLiaisonService(LiaisonService liaisonService) {
		this.liaisonService = liaisonService;
	}
	public PaginationSupport getPagination() {
		return pagination;
	}
	public void setPagination(PaginationSupport pagination) {
		this.pagination = pagination;
	}
	public Integer[] getIds() {
		return ids;
	}
	public void setIds(Integer[] ids) {
		this.ids = ids;
	}

	public void setCustomerService(CustomerService customerService) {
		this.customerService = customerService;
	}

	public CustomerService getCustomerService() {
		return customerService;
	}

	public void setCustomer(Customer customer) {
		this.customer = customer;
	}

	public Customer getCustomer() {
		return customer;
	}

	public void setLiaisonEvolves(List<LiaisonEvolve> liaisonEvolves) {
		this.liaisonEvolves = liaisonEvolves;
	}

	public List<LiaisonEvolve> getLiaisonEvolves() {
		return liaisonEvolves;
	}

	public void setLiaisonEvolveService(LiaisonEvolveService liaisonEvolveService) {
		this.liaisonEvolveService = liaisonEvolveService;
	}

	public LiaisonEvolveService getLiaisonEvolveService() {
		return liaisonEvolveService;
	}

	public void setLiaisonCostItemService(LiaisonCostItemService liaisonCostItemService) {
		this.liaisonCostItemService = liaisonCostItemService;
	}

	public LiaisonCostItemService getLiaisonCostItemService() {
		return liaisonCostItemService;
	}

	public void setLiaisonCostItems(List<LiaisonCostItem> liaisonCostItems) {
		this.liaisonCostItems = liaisonCostItems;
	}

	public List<LiaisonCostItem> getLiaisonCostItems() {
		return liaisonCostItems;
	}

	public void setLiaisonReasonService(LiaisonReasonService liaisonReasonService) {
		this.liaisonReasonService = liaisonReasonService;
	}

	public LiaisonReasonService getLiaisonReasonService() {
		return liaisonReasonService;
	}

	public void setLiaisonReasons(List<LiaisonReason> liaisonReasons) {
		this.liaisonReasons = liaisonReasons;
	}

	public List<LiaisonReason> getLiaisonReasons() {
		return liaisonReasons;
	}

	public void setLiaisonWayService(LiaisonWayService liaisonWayService) {
		this.liaisonWayService = liaisonWayService;
	}

	public LiaisonWayService getLiaisonWayService() {
		return liaisonWayService;
	}

	public void setLiaisonWays(List<LiaisonWay> liaisonWays) {
		this.liaisonWays = liaisonWays;
	}

	public List<LiaisonWay> getLiaisonWays() {
		return liaisonWays;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public void setItems(Integer[] items) {
		this.items = items;
	}

	public Integer[] getItems() {
		return items;
	}

	public void setNum(Double[] num) {
		this.num = num;
	}

	public Double[] getNum() {
		return num;
	}

	public void setLinkmans(List<Linkman> linkmans) {
		this.linkmans = linkmans;
	}

	public List<Linkman> getLinkmans() {
		return linkmans;
	}

	public void setLinkmanService(LinkmanService linkmanService) {
		this.linkmanService = linkmanService;
	}

	public LinkmanService getLinkmanService() {
		return linkmanService;
	}

	public void setCurrentDate(Date currentDate) {
		this.currentDate = currentDate;
	}

	public Date getCurrentDate() {
		return currentDate;
	}

	public void setUpLiaison(Liaison upLiaison) {
		this.upLiaison = upLiaison;
	}

	public Liaison getUpLiaison() {
		return upLiaison;
	}

	public void setCustomerAppointService(CustomerAppointService customerAppointService) {
		this.customerAppointService = customerAppointService;
	}

	public CustomerAppointService getCustomerAppointService() {
		return customerAppointService;
	}

	public CustomerLevelService getCustomerLevelService() {
		return customerLevelService;
	}

	public void setCustomerLevelService(CustomerLevelService customerLevelService) {
		this.customerLevelService = customerLevelService;
	}

	public List<CustomerLevel> getCustomerLevels() {
		return customerLevels;
	}

	public void setCustomerLevels(List<CustomerLevel> customerLevels) {
		this.customerLevels = customerLevels;
	}

	public void setLiaisonCritiqueService(LiaisonCritiqueService liaisonCritiqueService) {
		this.liaisonCritiqueService = liaisonCritiqueService;
	}

	public LiaisonCritiqueService getLiaisonCritiqueService() {
		return liaisonCritiqueService;
	}

	public void setLiaisonCritiques(Collection<LiaisonCritique> liaisonCritiques) {
		this.liaisonCritiques = liaisonCritiques;
	}

	public Collection<LiaisonCritique> getLiaisonCritiques() {
		return liaisonCritiques;
	}

	public void setLiaisonCritique(LiaisonCritique liaisonCritique) {
		this.liaisonCritique = liaisonCritique;
	}

	public LiaisonCritique getLiaisonCritique() {
		return liaisonCritique;
	}

	public String getTradeIds() {
		return tradeIds;
	}

	public void setTradeIds(String tradeIds) {
		this.tradeIds = tradeIds;
	}
	
}
